<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use App\Http\Requests;
use App\Http\Requests\GoodsRequest;
use App\Http\Requests\UpGoodsRequest;
use App\Http\Controllers\Controller;

use App\Http\Model\Goods;
use App\Http\Model\Menu;
use App\Http\Model\ClothingAttr;
use App\Http\Model\ClothingSpec;
use App\Http\Model\GoodsImage;
use App\Http\Model\User;
use App\Http\Model\Fenxiao;
use App\Http\Model\IntegralOrders;
use Config;
use Image;

class GoodsController extends Controller
{
    //
    public function goodsList(){
    	$goods = new Goods;
    	$goodsInfo = $goods->select("goods.*")->leftJoin("clothing_attr", "goods.id", "=", "goods_id")->where("status", "=", "0")->orWhere("status", "=", "1")->groupBy("goods.id")->get();
    	return view("admin.goods.goodsList", ['goodsInfo'=>$goodsInfo]);
    }
    public function goodsDetail($id){
        $goods = new Goods;
        $goodsInfo = $goods->find($id);
        return view("admin.goods.goodsDetail", ['goodsInfo'=>$goodsInfo]);
    }
    public function specialPrice(){
        $goods = new Goods;
        $goodsInfo = $goods->where("status", "=", "0")->orWhere("status", "=", "1")->get();
        return view("admin.goods.specialPrice", ['goodsInfo'=>$goodsInfo]);
    }
    public function exchange(){
        $goods = new Goods;
        $goodsInfo = $goods->where("status", "=", "0")->orWhere("status", "=", "1")->get();
        return view("admin.goods.exchange", ['goodsInfo'=>$goodsInfo]);
    }
    public function vip(){
        $goods = new Goods;
        $goodsInfo = $goods->where("status", "=", "0")->orWhere("status", "=", "1")->get();
        return view("admin.goods.vip", ['goodsInfo'=>$goodsInfo]);
    }
    public function goodsAdd(){
        $menu = new Menu;
        $clothingSpec = new ClothingSpec;
        $menuInfo = $menu->get();
        $clothingSpecInfo = $clothingSpec->get();
        return view("admin.goods.goodsAdd",["menuInfo"=>$menuInfo, "clothingSpecInfo"=>$clothingSpecInfo]);
    }
    public function goodsAddRes(GoodsRequest $request){
        // dd($request->all());
        $goods = new Goods;
        $menu = new Menu;
        $data = $request->all();
        // dd($data);
        $goods->name = $data['name'];
        $goods->spec = $data['spec'];
        $goods->menu_id = $data['menu_id'];
        $goods->pic = $this->uploadPic($request);
        $goods->express_price = $data['express_price'];
        $goods->describe = $data['describe'];
        $goods->save();
        for( $i=0; $i<6; $i++){
            if($request->file("url")[$i]){
                $goodsImage = new GoodsImage;
                $goodsImage->url = $this->uploadUrl($request, $i);
                $goodsImage->goods_id = $goods->id;
                $goodsImage->save();
            }
        }
        $this->addClothingAttr($request, $goods->id);
        // dd("123");
        return redirect('admin/goods-list')->with('success','商品新增成功');
    }
    public function addClothingAttr($request, $id){
        $specsArr = $request->input("specs");
        $priceArr = $request->input("price");
        $stockArr = $request->input("stock");
        foreach ($specsArr as $k => $v) {
            $clothingAttr = new ClothingAttr;
            $clothingAttr->goods_id = $id;
            $clothingAttr->clothing_spec_id = $v;
            $clothingAttr->price = $priceArr[$k];
            $clothingAttr->stock = $stockArr[$k];
            $clothingAttr->save();
        }
    }
    public function uploadPic($request){
        if($request->hasFile("pic")){
            $destinationPath = "./upload/goods/products/";
            $fileName = time().rand(100000,999999).'.'.$request->file("pic")->getClientOriginalExtension();
            Image::make($request->file("pic"))->resize(200, 200)->save($destinationPath.$fileName);
            // $request->file("pic")->move($destinationPath, $fileName);
            return "/products/".$fileName;die;
        }
    }
    public function uploadUrl($request,$num){
        $destinationPath = "./upload/goods/products/";
        $fileName = time().rand(100000,999999).'.'.$request->file("url")[$num]->getClientOriginalExtension();
        Image::make($request->file("url")[$num])->resize(750, 750)->save($destinationPath.$fileName);
        return "/products/".$fileName;die;
    }
    public function goodsUpdate($id){
        $menu = new Menu;
        $goods = new Goods;
        $clothingAttr = new ClothingAttr;
        $clothingSpec = new ClothingSpec;
        $menuInfo = $menu->get();
        $clothingSpecInfo = $clothingSpec->get();
        $goodsInfo = $goods->find($id);
        // dd($goodsInfo);
        return view("admin.goods.goodsUpdate",["menuInfo"=>$menuInfo, "clothingSpecInfo"=>$clothingSpecInfo, "goodsInfo"=>$goodsInfo]);
    }
    public function goodsUpdateRes(UpGoodsRequest $request){
        $goods = new Goods;
        $data = $request->all();
        $urls = array();
        $id = $data['id'];
        $goodsInfo = $goods->find($id);
        $goodsInfo->name = $data['name'];
        $goodsInfo->sales_volume = $data['sales_volume'];
        $goodsInfo->spec = $data['spec'];
        $goodsInfo->menu_id = $data['menu_id'];
        $goodsInfo->express_price = $data['express_price'];
        if($request->hasFile("pic")){
            @unlink("./upload/goods".$goodsInfo->pic);
            $goodsInfo->pic = $this->uploadPic($request);
        }
        for( $i=0; $i<6; $i++){
            if($request->file("url")[$i]){
                $goodsImage = new GoodsImage;
                if($goodsImageInfo = $goodsImage->where("goods_id",$goodsInfo->id)->skip($i)->take(1)->first()){
                    // echo $i;
                    array_push($urls, $goodsImageInfo->url);
                    $goodsImage = $goodsImageInfo;
                }
                $goodsImage->url = $this->updateUploadUrl($request, $i);
                $goodsImage->goods_id = $goodsInfo->id;
                $goodsImage->save();
            }
        }
        foreach ($urls as $k => $v) {
            @unlink("./upload/goods".$v);
        }
        $goodsInfo->describe = $data['describe'];
        // dd($goodsInfo);
        $goodsInfo->save();
        $this->updateClothingAttr($request);
        return redirect('admin/goods-list')->with('success','商品修改成功');
    }
    public function updateClothingAttr($request){
        $data = $request->all();
        $urls = array();
        foreach ($data["specs"] as $k => $v) {
            $clothingAttr = new ClothingAttr;
            if($k != 0){
                $clothingAttrInfo = $clothingAttr->find($k);
                $clothingAttrInfo->clothing_spec_id = $data["specs"][$k][0];
                $clothingAttrInfo->price = $data["price"][$k][0];
                $clothingAttrInfo->stock = $data["stock"][$k][0];
                $clothingAttrInfo->save();
            }else{
                $specArr = $data["specs"][0];
                $priceArr = $data["price"][0];
                $stockArr = $data["stock"][0];
                foreach ($specArr as $k => $v) {
                    $clothingAttr = new ClothingAttr;
                    $clothingAttr->clothing_spec_id = $v;
                    $clothingAttr->price = $priceArr[$k];
                    $clothingAttr->stock = $stockArr[$k];
                    $clothingAttr->goods_id = $data['id'];
                    $clothingAttr->save();
                }
            }
        }
    }
    public function updateUploadUrl($request, $num){
        $destinationPath = "./upload/goods/products/";
        $fileName = time().rand(100000,999999).'.'.$request->file("url")[$num]->getClientOriginalExtension();
        $request->file("url")[$num]->move($destinationPath, $fileName);
        return "/products/".$fileName;die;
    }
    public static function getMenu($id){
    	$menu = new Menu;
    	$menuInfo = $menu->find($id);
    	return $menuInfo;
    }
    // 积分设置
    public function integralSet(){
        $fenxiao = new Fenxiao;
        $integralInfo = $fenxiao->select("id","integral_exchange_money","money_exchange_integral")->first();
        return view("admin.goods.integral-set", ["integralInfo"=>$integralInfo]);
    }

    // 积分设置处理
    public function integralSetRes(Request $request){
        // dd($request->all());
        $fenxiao = new Fenxiao;
        $integralInfo = $fenxiao->find($request->input("id"));
        $integralInfo->integral_exchange_money = $request->input("integral_exchange_money");
        $integralInfo->money_exchange_integral = $request->input("money_exchange_integral");
        $integralInfo->save();
        return redirect("/admin/integral-set")->with("success", "积分设置成功");
    }
    // 兑换列表
    public function integralExchangeList(){
        $integralOrders= new IntegralOrders;
        $integralOrdersInfo = $integralOrders->get();
        return view("admin.orders.integral-exchange-list", ["integralOrdersInfo"=>$integralOrdersInfo]);
    }
    // 兑换详情
    public function ordersIntegralDetail($id){
        $integralOrders = new IntegralOrders;
        $integralOrdersInfo = $integralOrders->find($id);
        return view("admin.orders.orders-integral-detail", ["integralOrdersInfo"=>$integralOrdersInfo]);
    }
    // 兑换发货
    public function integralExchangeSend(){
        $integralOrders= new IntegralOrders;
        $integralOrdersInfo = $integralOrders->where("status",0)->get();
        return view("admin.orders.integral-exchange-send", ["integralOrdersInfo"=>$integralOrdersInfo]);
    }
    // 兑换发货处理
    public function integralSend(Request $request){
        $integralOrders = new IntegralOrders;
        $integralOrdersInfo = $integralOrders->find($request->input("id"));
        $integralOrdersInfo->logistic_code = $request->input("logistic_code");
        $integralOrdersInfo->status = 1;
        $integralOrdersInfo->save();
        echo 1;die;
    }
    // 兑换物流查询
    public function integralOrdersLogistic($id){
        $integralOrders = new IntegralOrders;
        $integralOrdersInfo = $integralOrders->find($id);
        $num = $integralOrdersInfo->orders_num;
        // $num = '51010904478878935';
        $logistic_code = $integralOrdersInfo->logistic_code;
        // $logistic_code = '3976331681071';
        $logistic_company = Config::get('app.kdn_company_name');
        // $logistic_company = "YD";
        $logisticResult = json_decode($this->getOrderTracesByJson($num, $logistic_code, $logistic_company));
        return view("admin.orders.logistic", ["logistic"=>$logisticResult]);
    }

    public function changeStatus(Request $request){
        $goods_id = $request->input("goods_id");
        $status = $request->input("status");
        $goods = new Goods;
        $nowTime = date("Y-m-d H:i:s");
        $result = $goods->where('id', $goods_id)->update(['status' => $status, 'updated_at'=>$nowTime]);
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    //设置热销商品
    public function changeGoodsType(Request $request){
        $goods_id = $request->input("goods_id");
        $goodsType = $request->input("goodstype");
        $goods = new Goods;
        $nowTime = date("Y-m-d H:i:s");
        $result = $goods->where('id', $goods_id)->update(['goods_type' => $goodsType, 'updated_at'=>$nowTime]);
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    // public function changeClothingStatus(Request $request){
    //     $id = $request->input("id");
    //     $status = $request->input("status");
    //     $clothingAttr = new ClothingAttr;
    //     $nowTime = date("Y-m-d H:i:s");
    //     $result = $clothingAttr->where('id', $id)->update(['status' => $status, 'updated_at'=>$nowTime]);
    //     if($result){
    //         echo 1;die;
    //     }else{
    //         echo 0;die;
    //     }
    // }
    public function delete(Request $request){
        $goods_id = $request->input("goods_id");
        $goods = new Goods;
        $nowTime = date("Y-m-d H:i:s");
        $result = $goods->where('id', $goods_id)->update(['status' => 2, 'updated_at'=>$nowTime]);
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    public function deleteClothingAttr(Request $request){
        $clothingAttr = new ClothingAttr;
        $clothingAttr_id = $request->input("clothingAttr_id");
        $result = $clothingAttr->where('id', $clothingAttr_id)->delete();
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    public function deleteImage(Request $request){
        $goodsImage = new GoodsImage;
        $goods_image_id = $request->input("goods_image_id");
        $goodsImageInfo = $goodsImage->find($goods_image_id);
        @unlink("./upload/goods".$goodsImageInfo->url);
        $result = $goodsImageInfo->delete();
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    public function updateExchange(Request $request){
        $goods = new Goods;
        $id = $request->input("id");
        $exchange = $request->input("exchange");
        $goodsInfo = $goods->find($id);
        $goodsInfo->exchange = $exchange;
        $goodsInfo->save();
        echo 1;die;
    }
    public function updateExchangeStatus(Request $request){
        $id = $request->input("id");
        $exchange_status = $request->input("exchange_status");
        $goods = new Goods;
        $goodsInfo = $goods->find($id);
        $goodsInfo->exchange_status = $exchange_status;
        $result = $goodsInfo->save();
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    public function updateSpecialPrice(Request $request){
        $goods = new Goods;
        $id = $request->input("id");
        $special_price = $request->input("special_price");
        $goodsInfo = $goods->find($id);
        $goodsInfo->special_price = $special_price;
        $goodsInfo->save();
        echo 1;die;
    }
    public function updateSpecialPriceStatus(Request $request){
        $id = $request->input("id");
        $special_price_status = $request->input("special_price_status");
        $goods = new Goods;
        $goodsInfo = $goods->find($id);
        $goodsInfo->special_price_status = $special_price_status;
        $result = $goodsInfo->save();
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    public function updateVip(Request $request){
        $goods = new Goods;
        $id = $request->input("id");
        $vip = $request->input("vip");
        $goodsInfo = $goods->find($id);
        $goodsInfo->vip = $vip;
        $goodsInfo->save();
        echo 1;die;
    }
    public function updateVipStatus(Request $request){
        $id = $request->input("id");
        $vip_status = $request->input("vip_status");
        $goods = new Goods;
        $goodsInfo = $goods->find($id);
        $goodsInfo->vip_status = $vip_status;
        $result = $goodsInfo->save();
        if($result){
            echo 1;die;
        }else{
            echo 0;die;
        }
    }
    //商品模板消息推送
    public function pushGoods(Request $request){
        $goods = new Goods;
        $user = new User;
        $id = $request->input('goods_id');
        $goodsInfo = $goods->find($id);
        $userInfo = $user->select('open_id')->get();
        $app = app('wechat');
        $notice = $app->notice;
        $url1 = Config::get('app.domain_name').'detail/'.$id;
        $app_id = Config::get('wechat.app_id');
        $url2 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$url1."&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/";
        $template_id = 'sW08S44rRz59qG7RCA1cmxYBTjQMeO2G_wtOR6XhfSE';
        $data = array(
            "first"=>'您好，新品上架请查看！',
            "keyword1"=>'天路本草旗舰店',
            "keyword2"=>$goodsInfo->name,
            "keyword3"=>$goodsInfo->clothingAttrLow->first()->price,
            "remark"=>'感谢您的支持！',
        );
        foreach ($userInfo as $key => $value) {
            $notice->uses($template_id)->withUrl($url2)->andData($data)->andReceiver($value->open_id)->send();
        }
        echo 1;die;
    }

    /**
     * Json方式 查询订单物流轨迹
     */
    public function getOrderTracesByJson($num, $logistic_code, $logistic_company){
        $requestData = "{'OrderCode':'$num','ShipperCode':'$logistic_company','LogisticCode':'$logistic_code'}";

        $datas = array(
            'EBusinessID' => Config::get('app.kdn_user_id'),
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, Config::get('app.kdn_api_key'));
        $result = $this->sendPost('http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx', $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }

}
